package com.heima.search.Service.impl;

import com.heima.common.dtos.ResponseResult;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.Service.ApUserSearchService;
import com.heima.utils.common.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    @Async
    public void insert(Integer userId, String keyword) {

        //查询该用户是否搜索过该关键词
        Query query = Query.query(Criteria.where("userId").is(userId).and("keyword").is(keyword));
        ApUserSearch userSearch = mongoTemplate.findOne(query, ApUserSearch.class);
        if(userSearch!=null){
            //存在该关键词，则更新为最新时间
            userSearch.setCreatedTime(new Date());
            mongoTemplate.save(userSearch);//如果id存在，则为更新数据
            return;
        }

        ApUserSearch newUserSearch = new ApUserSearch();
        newUserSearch.setCreatedTime(new Date());
        newUserSearch.setUserId(userId);
        newUserSearch.setKeyword(keyword);

        //查询当前用户的历史记录
        Query userQuery = Query.query(Criteria.where("userId").is(userId));
        //对createdTime倒序
        userQuery.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApUserSearch> searchList = mongoTemplate.find(userQuery, ApUserSearch.class);

        if(searchList==null || searchList.size()<10){
            //直接存入数据库
            mongoTemplate.save(newUserSearch);
        }else{
            //替换searchList的最后一条记录

            /**
             * 查找并替换
             *   参数一：Query对象，查询条件
             *   参数二：替换后的对象
             */
            //取出最后一条记录
            ApUserSearch apUserSearch = searchList.get(searchList.size() - 1);
            mongoTemplate.findAndReplace( Query.query(Criteria.where("_id").is(apUserSearch.getId())) ,newUserSearch);
        }
    }

    @Override
    public ResponseResult<List<ApUserSearch>> load() {
        ApUser apUser = (ApUser)ThreadLocalUtils.get();
        if(apUser==null){ // 访客没有搜索记录
            return ResponseResult.okResult(null);
        }

        Query query = Query.query(Criteria.where("userId").is(apUser.getId()));
        query.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApUserSearch> searchList = mongoTemplate.find(query, ApUserSearch.class);

        return ResponseResult.okResult(searchList);
    }

    @Override
    public ResponseResult del(HistorySearchDto dto) {
        Query query = Query.query(Criteria.where("_id").is(dto.getId()));
        return ResponseResult.okResult(mongoTemplate.remove(query,ApUserSearch.class));
    }
}
